package com.first.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.first.common.constant.MessageConstant;
import com.first.common.context.BaseContext;
import com.first.common.exception.PasswordErrorException;
import com.first.common.result.PageResult;
import com.first.pojo.dto.AdminLoginDTO;
import com.first.pojo.dto.UserPageQueryDTO;
import com.first.pojo.entity.Admin;
import com.first.pojo.entity.User;
import com.first.pojo.vo.UserPageQueryVO;
import com.first.server.mapper.AdminMapper;
import com.first.server.mapper.PlaceMapper;
import com.first.server.mapper.UserMapper;
import com.first.server.mapper.UserPlaceMapper;
import com.first.server.service.UserService;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.security.auth.login.AccountNotFoundException;
import com.github.pagehelper.PageHelper;

@Service
@Slf4j
public class UserServiceImpl implements UserService {



    @Autowired
    UserMapper userMapper;
    @Autowired
    PlaceMapper placeMapper;
    @Autowired
    UserPlaceMapper userPlaceMapper;
    @Autowired
    AdminMapper adminMapper;


    @Override
    public PageResult pageQuery(UserPageQueryVO userPageQueryVO) {
        UserPageQueryDTO userPageQueryDTO=new UserPageQueryDTO();
        BeanUtils.copyProperties(userPageQueryVO,userPageQueryDTO);
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        userPageQueryDTO.setPlaceId(Math.toIntExact(BaseContext.getCurrentPlaceId()));
        Page<User> page = userMapper.pageQuery(userPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 管理员登录
     * @param adminLoginDTO
     * @return
     * @throws AccountNotFoundException
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) throws AccountNotFoundException {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().lambda().eq(Admin::getUsername, username));

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }


        //3、返回实体对象
        return admin;
    }



}
